package com.geekcoding.geekoj.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geekcoding.common.dto.ApiResponse;
import com.geekcoding.common.dto.BasePageQuery;
import com.geekcoding.geekoj.dto.QuestionDTO;
import com.geekcoding.geekoj.entity.TestAnswer;
import com.geekcoding.geekoj.mapper.TestAnswerMapper;
import com.geekcoding.geekoj.repository.*;
import com.geekcoding.geekoj.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

@RestController()
@RequestMapping("/api/admin/answer")
public class AdminAnswerController extends BaseAdminController<TestAnswer, TestAnswer, TestAnswerMapper, TestAnswerRepository> {

    private final QuestionRepository questionRepository;

    private final TestRepository testRepository;

    public AdminAnswerController(TestAnswerRepository repository, UserService userService, QuestionRepository questionRepository, TestRepository testRepository) {
        super(repository, userService);
        this.questionRepository = questionRepository;
        this.testRepository = testRepository;
    }


    @PostMapping("/list")
    public ApiResponse pageList(@RequestBody BasePageQuery query) {
        Page<TestAnswer> tPage = repository.queryByPage(Page.of(query.getCurrent(), query.getPageSize()), null);
        Page<QuestionDTO> page = new Page<>(tPage.getCurrent(), tPage.getSize(), tPage.getTotal());
        if (CollectionUtil.isNotEmpty(tPage.getRecords())) {
            page.setRecords(tPage.getRecords().stream().map(answer -> QuestionDTO.convert(questionRepository.queryById(
                    answer.getQuestionId()), testRepository.queryById(answer.getTestId()))).collect(Collectors.toList()));
        }
        return ApiResponse.success(page);
    }
}
